<?php
/**
 * XML Document Class
 * 
 * @version	1.0
 * @author	Endel Dreyer
 * @license	GNU GENERAL PUBLIC LICENSE ( http://www.gnu.org/licenses/gpl-3.0.txt )
 * @date	2007-07-11
 * @link	http://code.google.com/p/php-xml-document/
 */

class xml_document {
	var $version = "1.0";
	var $encoding = "UTF-8";
	var $_name;
	var $_content = array();
	function xml_document($name) {
		$this->_name = $name;
	}
	function setVersion($version) {
		$this->version = $version;
	}
	function setEncode($encoding) {
		$this->encoding = $encoding;
	}
	function &addNode($nodeName,$nodeContent = null) {
		$this->_content[] = new node($nodeName,$nodeContent);
		$nodeObject =& $this->_content[count($this->_content)-1];
		return $nodeObject;
	}
	
	function save($path) {
		if (!is_dir($path)) {
			mkdir($path);
			chmod($path,777);
		}
		$saveFile = fopen("$path/$this->_name.xml","w");
		return fwrite($saveFile,$this->content());
	}
	function content() {
		$xml_content = "<?xml version=\"$this->version\" encoding=\"$this->encoding\"?>";
		foreach ($this->_content as $node) {
			$xml_content .= $node->_dump(0);
		}
		return $xml_content;
	}
}

class node {
	var $_name;
	var $_content = array();
	var $_attributes = array();
	
	function node($name,$content) {
		$this->_name = $name;
		if ($content != null)
		$this->_content = $content;
	}
	function &addNode($nodeName,$nodeContent = null) {
		$this->_content[] = new node($nodeName,$nodeContent);
		$nodeObject =& $this->_content[count($this->_content)-1];
		return $nodeObject;
	}
	function addAttribute($name,$content) {
		$this->_attributes[$name] = $content;
	}
	function _dump($hierarchy = 0) {
		$hierarchy_add = "\n".str_repeat("\t",$hierarchy);
		$return = $hierarchy_add."<$this->_name";
		foreach ($this->_attributes as $attr_name => $attr_value) {
			$return .= " $attr_name=\"$attr_value\"";
		}
		$return .= ">";
		if (is_array($this->_content)) {
			if (!empty($this->_content)) {
				foreach ($this->_content as $node) {
					$return .= $node->_dump($hierarchy+1);
				}
			}
		} elseif (!empty($this->_content)) {
			if (strpos($this->_content,"\n")>0)
				$return .= $hierarchy_add."\t";
			$return .= $this->_content;
		}
		$breakfinal = (is_string($this->_content) || is_null($this->_content)) ? "" : $hierarchy_add ;
		$return .= $breakfinal."</$this->_name>";
		return $return;
	}
}
?>